package com.plian.system.controller.im;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.entity.im.BaseInvestmentDebt;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.im.IBaseInvestmentDebtService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.im.BaseInvestmentDebtVO;
import com.plian.system.wrapper.im.BaseInvestmentDebtWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;

/**
 * 控制器
 *
 * @author
 * @since 2019-09-27
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("api/baseinvestmentdebt")
@Api(value = "TripleEventController", tags = "投资项目债务主要信息表 控制器")
public class BaseInvestmentDebtController extends BaseController {

	private IBaseInvestmentDebtService baseInvestmentDebtService;

	private FormWorkflowService formWorkflowService;

	private BaseInvestmentDebtWrapper baseInvestmentDebtWrapper;

	/**
	 * 详情
	 */
	@PostMapping("/detail")
	@ApiOperation(value = "详情")
	public R<BaseInvestmentDebtVO> detail(@RequestBody BaseInvestmentDebt baseInvestmentDebt) {
		BaseInvestmentDebt detail = baseInvestmentDebtService.getOne(Condition.getQueryWrapper(baseInvestmentDebt));
		BaseInvestmentDebtVO baseInvestmentDebtVO = baseInvestmentDebtWrapper.entityToVO(detail);
		return baseInvestmentDebtService.getDetailObj(baseInvestmentDebtVO);
	}

	/**
	 * 分页
	 */
	@PostMapping("/list")
	@ApiOperation(value = "分页")
	public ListResult<BaseInvestmentDebtVO> list(@RequestBody Query query) {
		List<SearchEntity> entityList = query.getSearch();
		if (query.getAscs()==null&&query.getDescs()==null){
			query.setDescs("create_time");
		}
		QueryWrapper<BaseInvestmentDebt> queryWrapper = SearchParamEntiy.getQueryWrapper(
				Condition.getQueryWrapper(new BaseInvestmentDebt()), entityList
		);
		TokenSearch<BaseInvestmentDebt> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);

		IPage<BaseInvestmentDebt> pages = baseInvestmentDebtService.page(Condition.getPage(query), queryWrapper);
		List<BaseInvestmentDebtVO> baseInvestmentDebtVOS = baseInvestmentDebtWrapper.entityToVO(pages.getRecords());
		ListResult<BaseInvestmentDebtVO> listResult = new ListResult<>(CommonCode.SUCCESS);
		listResult.setList(baseInvestmentDebtVOS);
		listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
		return listResult;
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@Resubmit(delaySeconds = 0)
	@LogOperation("投资项目债务主要信息-保存")
	@ApiOperation(value = "新增或修改")
	public R submit(@Valid @RequestBody BaseInvestmentDebt baseInvestmentDebt) {
		String checkMessage = baseInvestmentDebtService.checkMonth(baseInvestmentDebt);
		if (StringUtil.isNotBlank(checkMessage)){
			return new R(CustomCode.builder().message(checkMessage).code(1999).success(false).build());
		}

		boolean result = baseInvestmentDebtService.submit(baseInvestmentDebt);
		HashMap<String, Object> processVariable = new HashMap<>();
		formWorkflowService.startProcessAndSimulate(String.valueOf(baseInvestmentDebt.getId()),baseInvestmentDebt.getFormType(),processVariable);

		return result ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperation(value = "删除")
	@LogOperation("投资项目债务主要信息-删除")
	public R remove(@RequestBody PageData pd) {
		List<String> ids = (List<String>)pd.get("ids");
		return baseInvestmentDebtService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
				? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
	}

	/**
	 * 生成excel文件
	 * @param id
	 * @return
	 */
	@GetMapping("/export/{id}")
	@ApiOperation(value = "生成excel文件")
	public ObjResult export(@PathVariable Long id){
		PageData pd = new PageData();
		pd.put("key", baseInvestmentDebtService.export(id));
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		objResult.setPageData(pd);
		return objResult;
	}

//	/**
//	 * 生成可以导入的excel文件
//	 * @param id
//	 * @return
//	 */
//	@GetMapping("/exportImportFile/{id}")
//	@ApiOperation(value = "生成可以导入的excel文件")
//	public ObjResult exportImportFile(@PathVariable Long id){
//		PageData pd = new PageData();
//		pd.put("key", baseInvestmentDebtService.exportImportFile(id));
//		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
//		objResult.setPageData(pd);
//		return objResult;
//	}

	/**
	 * 下载excel文件 并删除
	 * @param key
	 * @param response
	 * @param os
	 */
	@GetMapping("/download/{key}")
//	@PassToken
	@ApiOperation(value = "下载excel文件 并删除")
	public void download(@PathVariable String key, HttpServletResponse response, OutputStream os){
		baseInvestmentDebtService.download(key, response, os);
	}

	/**
	 * 获取上月填报数据
	 * @param baseInvestmentDebt
	 * @return
	 */
	@PostMapping("/last")
	@ApiOperation(value = "获取上月填报数据")
	public R<BaseInvestmentDebtVO> last(@RequestBody BaseInvestmentDebt baseInvestmentDebt) {
		return baseInvestmentDebtService.getLastMonthObj(baseInvestmentDebt);
	}

	/**
	 * 债务余额及结构主表填报树
	 * @param baseInvestmentDebt
	 * @return
	 */
	@PostMapping("/tree")
	@ApiOperation(value = "债务余额及结构主表填报树")
	public ObjResult tree(@RequestBody BaseInvestmentDebt baseInvestmentDebt){
		return baseInvestmentDebtService.tree(baseInvestmentDebt);
	}

	/**
	 * 树列表 分页
	 */
	@PostMapping("/treeList")
	@ApiOperation(value = "树列表 分页")
	public ListResult<PageData> treeList(@RequestBody Query query) {
		return baseInvestmentDebtService.treeList(query);
	}


	/**
	 * 债务余额及结构主表填报树 新增
	 * @param baseInvestmentDebt
	 * @return
	 */
	@PostMapping("/add/tree")
	@Resubmit(delaySeconds = 0)
	@LogOperation("投资项目债务主要信息-债务余额及结构主表填报树-保存")
	@ApiOperation(value = "债务余额及结构主表填报树 新增")
	public ObjResult addTree(@RequestBody BaseInvestmentDebt baseInvestmentDebt){
		return baseInvestmentDebtService.addTree(baseInvestmentDebt);
	}

	/**
	 * 获取下级已填报数据
	 * @param baseInvestmentDebt
	 * @return
	 */
	@PostMapping("/childList")
	@ApiOperation(value = "获取下级已填报数据")
	public ObjResult childList(@RequestBody BaseInvestmentDebt baseInvestmentDebt){
		return baseInvestmentDebtService.childList(baseInvestmentDebt);
	}

//	/** TODO DEL
//	 * 根据主表id 获取合计数据
//	 * @param baseInvestmentDebt
//	 * @return
//	 */
//	@PostMapping("/childSummary")
//	@ApiOperation(value = "根据主表id 获取合计数据")
//	public ObjResult childSummary(@RequestBody BaseInvestmentDebt baseInvestmentDebt){
//		return baseInvestmentDebtService.childSummary(baseInvestmentDebt);
//	}

	/**
	 * 模板下载
	 * @param response
	 * @param os
	 */
	@GetMapping("/exportTemplateExcel")
//	@PassToken
	@ApiOperation(value = "模板下载")
	public void exportTemplateExcel(HttpServletResponse response, OutputStream os){
		baseInvestmentDebtService.exportTemplateExcel(response, os);
	}
//	/**
//	 * 覆盖导入 根据填报时间 填报单位覆盖或新增
//	 */
//	@PostMapping("/excelCoverImport")
//	@ApiOperation(value = "覆盖导入 根据填报时间 填报单位覆盖或新增")
//	public ObjResult excelCoverImport(@RequestParam("file") MultipartFile multipartFile) throws IOException {
//		String progressId = TokenUtil.getTokenUserId() + "_"+System.currentTimeMillis();
//		CacheUtil.put("progress","progress",progressId + "#half:hour",0);
//		InputStream inputStream = multipartFile.getInputStream();
//		baseInvestmentDebtService.importExcel(progressId, inputStream);
//		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
//		PageData pd = new PageData();
//		pd.put("progressId", progressId);
//		objResult.setPageData(pd);
//		return objResult;
//	}

	/**
	 * 导入进度查看
	 */
	@GetMapping("/progress/{progressId}")
	@ApiOperation(value = "导入进度查看")
	public ObjResult progress(@PathVariable String progressId){
		Object data = CacheUtil.get("progress", "progress", progressId + "#half:hour");
		if(data != null && data instanceof String){
			if ("导入成功".equals(data)){
				ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
				PageData pd = new PageData();
				pd.put("data", 200);
				objResult.setPageData(pd);
				return objResult;
			}
			return new ObjResult(CustomCode.builder().message((String)data).code(1000).success(false).build());
		}
		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
		PageData pd = new PageData();
		pd.put("data", data);
		objResult.setPageData(pd);
		return objResult;
	}

//	@PostMapping("/summary")
//	public ListResult<InvestmentDebtSummaryVO>  summary(@RequestBody BaseInvestmentDebtDTO baseInvestmentDebtDTO){
//		ListResult listResult = new ListResult(CommonCode.SUCCESS);
//		listResult.setList(baseInvestmentDebtService.summary(baseInvestmentDebtDTO));
//		return listResult;
//	}
//
//	/**
//	 * 生成汇总表excel
//	 * @param baseInvestmentDebtDTO
//	 * @return
//	 */
//	@PostMapping("/summary/export")
//	@ApiOperation(value = "生成汇总表excel")
//	public ObjResult summaryExport(@RequestBody BaseInvestmentDebtDTO baseInvestmentDebtDTO){
//		PageData pd = new PageData();
//		pd.put("key", baseInvestmentDebtService.summaryExport(baseInvestmentDebtDTO));
//		ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
//		objResult.setPageData(pd);
//		return objResult;
//	}
}
